<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { useFallBack } from '../useFallBack';
import useUserStore from '@/store/modules/user';

const dataIsReady = ref(false);
const loading = ref<boolean>(false);
const data = ref<any[]>([]);
const total = ref<number>(0);
const pageSize = ref<number>(10);
const current = ref<number>(1);
// 获取数据
async function getAllPictureData() {
  data.value = [];
  loading.value = true;
  await getAllPicturesPage(current.value, pageSize.value).then((res: any) => {
    total.value = res.data.total;
    data.value = res.data.records;
    dataIsReady.value = true;
  }).finally(() => {
    loading.value = false;
  });
}

onMounted(async () => {
  getAllPictureData();
});

// 日期格式修改
function formatDate(isoDateString: any) {
  if (!isoDateString || isoDateString === '') {
    return '';
  }
  const date = new Date(isoDateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 下载图片
async function downImg(imgsrc: string, name: string, imgid: number) {
  // 获取用户信息
  const userStore = useUserStore();
  const tokenname = userStore.userId;
  // 点击下载图片更新数据库
  await clickToDownload(imgid, tokenname.toString());
  getAllPictureData();
  // 下载图片
  if (imgsrc.toLowerCase().endsWith('.mp4')) {
    const fileName = 'video.mp4';
    const a = document.createElement('a');
    a.style.display = 'none';
    document.body.appendChild(a);
    const xhr = new XMLHttpRequest();
    xhr.open('GET', imgsrc, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (xhr.status === 200) {
        const videoBlob = xhr.response;
        const url = window.URL.createObjectURL(videoBlob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
      }
    };
    xhr.send();
  }
  else {
    imgsrc = `${imgsrc}?v=${Math.random()}`;
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      if (context) {
        context.drawImage(image, 0, 0, image.width, image.height);
      }
      const url = canvas.toDataURL('image/png');
      const a = document.createElement('a');
      const event = new MouseEvent('click');
      a.download = name || 'photo';
      a.href = url;
      a.dispatchEvent(event);
    };
    image.src = imgsrc;
  }
}

// 判断是否为视频
function isMp4(link: any) {
  return link.toLowerCase().endsWith('.mp4');
}

// 搜索
const value = ref<string>('');
async function onSearch() {
  await Picturesearch(value.value).then((res: any) => {
    message.success('搜索成功!');
    data.value = res.data;
  });
}

// 预览
const visible = ref<boolean>(false);
const imgItem = ref<any>();
function showModal(record: any) {
  imgItem.value = record;
  visible.value = true;
}
// 分页
async function onShowSizeChange(c: number, p: number) {
  data.value = [];
  loading.value = true;
  await getAllPicturesPage(c, p).then((res: any) => {
    total.value = res.data.total;
    data.value = res.data.records;
    dataIsReady.value = true;
  }).finally(() => {
    loading.value = false;
  });
}
watch(pageSize, async () => {
  data.value = [];
  loading.value = true;
  await getAllPicturesPage(current.value, pageSize.value).then((res: any) => {
    total.value = res.data.total;
    data.value = res.data.records;
    dataIsReady.value = true;
  }).finally(() => {
    loading.value = false;
  });
});
watch(current, async () => {
  data.value = [];
  loading.value = true;
  await getAllPicturesPage(current.value, pageSize.value).then((res: any) => {
    total.value = res.data.total;
    data.value = res.data.records;
    dataIsReady.value = true;
  }).finally(() => {
    loading.value = false;
  });
});
</script>

<template>
  <div>
    <div class="header">
      <div class="right">
        <a-space>
          <a-input-search
            v-model:value="value" placeholder="请输入关键字" enter-button style="width: 15vw;"
            @search="onSearch"
          />
        </a-space>
      </div>
    </div>
    <div class="list-container">
      <a-card v-for="(item, index) in data" :key="index" class="list-item-bordered" hoverable>
        <template #cover>
          <div v-if="isMp4(item.link)">
            <video :src="item.link" style="width: 100%;height: 18vw;" @click="showModal(item)" />
          </div>
          <a-image
            v-else :src="item.link" :alt="item.title" style="width: 100%;height: 18vw;" loading="lazy"
            :fallback="useFallBack().fallback"
          />
        </template>
        <a-card-meta>
          <template #description>
            <a-tooltip placement="right">
              <template #title>
                <p>部门：{{ item.department }}</p>
                <p>主要人员: {{ item.mainPersonnel }}</p>
                <p>活动地点：{{ item.eventLocation }}</p>
                <p>类型：{{ item.eventType }}</p>
                <p v-if="item.event !== null">
                  事件类型：{{ item.event }}
                </p>
                <p v-else>
                  事件类型
                </p>
              </template>
              <div class="item-description">
                <span class="item-title">事件名称：{{ item.eventName }}</span>
              </div>
              <div class="item-description2">
                <div>活动时间：{{ formatDate(item.eventTime) }}</div>
                <div>标签：{{ item.tags }}</div>
                <div>下载次数：{{ item.downloadCount }}</div>
              </div>
              <div class="item-button">
                <span />
                <a-button style=" width: 4.5vw;height: 2.5vw;font-size: 1vw;line-height: 2vw;text-align: center;" @click="downImg(item.link, item.title, item.id)">
                  下载
                </a-button>
              </div>
            </a-tooltip>
          </template>
        </a-card-meta>
      </a-card>
      <a-modal v-model:visible="visible" footer="">
        <div v-if="isMp4(imgItem.link)">
          <video :src="imgItem.link" style="width: 100%;height: 18vw;" controls />
        </div>
        <a-image
          v-else :src="imgItem.link" :alt="imgItem.title" style="width: 100%;height: 18vw;" loading="lazy"
          :fallback="useFallBack().fallback"
        />
      </a-modal>
    </div>
    <div style="display: grid; width: 100%;">
      <div id="components-pagination-demo-mini" style=" justify-self: end;">
        <a-pagination
          v-model:current="current" v-model:pageSize="pageSize" :total="total"
          show-size-changer show-quick-jumper @show-size-change="onShowSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 3vw;
  margin-bottom: 0.5vw;

  .pjTitle {
    padding-left: 2vw;
    background: url("@/assets/images/title-left-bg.svg") no-repeat;
  }

  .right {
    display: flex;
    align-items: center;
  }
}

.list-container {
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  gap: 1vw;
  max-width: 100%;
  padding: 0.5vw;
  // overflow-y: auto;
}

.list-item-bordered {
  box-sizing: border-box;
  width: calc(25% - 1vw);

  .item-description {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 100%;
    overflow: hidden;
    line-height: 2vw;

    .item-title {
      font-size: 1.3vw;
      font-weight: 550;
      color: black;
      white-space: nowrap;
    }

    span {
      font-size: 1vw;
      white-space: nowrap;
    }
  }

  .item-description2 {
    align-items: center;
    justify-content: space-between;
    max-width: 100%;

    div {
      font-size: 1vw;
      white-space: nowrap;
    }
  }

  .item-button {
    display: flex;

    span {
      flex: 1;
      font-size: 1.5vw;
      white-space: nowrap;
    }
  }
}

.card-actions a {
  display: inline-block;
  margin-top: 1.067vw;
}

#components-pagination-demo-mini .ant-pagination:not(:last-child) {
  margin-bottom: 3.2vw;
}
</style>
